<?php

namespace App\Console\Commands;

use App\Models\Family;
use App\Models\Project;
use App\Models\Team;
use App\Models\User;
use App\Models\UserProject;
use App\Models\Volunteer;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class RefreshFamily extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'refreshFamily';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '更新家庭成员';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //
        Log::info('refresh family info');

        $nodes = Volunteer::selectRaw('family_id, count(*) as ct, sum(reward_time) as service_time_long, group_concat(user_id) as ids')->groupBy('family_id')->get();

        foreach($nodes as $value)
        {
            $joinCount = UserProject::whereRaw("user_id in ($value->ids)")->where('verify_status', 1)->where('reward_time', '>', 0)->count();

            Family::where('id', $value->family_id)->update(['join_project_count'=>$joinCount, 'member_count'=>$value->ct, 'service_time_long'=>$value->service_time_long]);

        }
    }
}
